<template>
  <div class="tax-identity-management">
    <!-- 搜索栏 -->
    <div class="search-bar">
      <el-form :inline="true" :model="searchForm" class="search-form">
        <el-form-item label="批次号">
          <el-input v-model="searchForm.batchCode" placeholder="请输入批次号" clearable
                    style="width: 180px"/>
        </el-form-item>
        <el-form-item label="统一社会信用代码">
          <el-input v-model="searchForm.creditCode" placeholder="请输入统一社会信用代码" clearable
                    style="width: 180px"/>
        </el-form-item>
        <el-form-item label="报送状态">
          <el-select v-model="searchForm.reportStatus" placeholder="请选择状态" clearable style="width: 120px">
            <el-option label="待报送" :value="0"/>
            <el-option label="报送中" :value="1"/>
            <el-option label="报送成功" :value="2"/>
            <el-option label="报送失败" :value="3"/>
            <el-option label="待作废" :value="4"/>
            <el-option label="作废中" :value="5"/>
            <el-option label="作废成功" :value="6"/>
            <el-option label="作废失败" :value="7"/>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="search">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="header-actions">
      <el-button type="primary" @click="showCreateDialog">
        <el-icon>
          <Plus/>
        </el-icon>
        新增
      </el-button>
      <el-button type="danger" @click="batchDelete" :disabled="selectedIds.length === 0">
        <el-icon>
          <Delete/>
        </el-icon>
        批量删除
      </el-button>
    </div>

    <!-- 数据表格 -->
    <el-table
        :data="tableData"
        style="width: 100%"
        v-loading="loading"
        @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55"/>
      <el-table-column prop="id" label="ID"/>
      <el-table-column prop="batchCode" label="批次" width="100"/>
      <el-table-column prop="taxpayerName" label="纳税人名称" min-width="240"/>
      <el-table-column prop="creditCode" label="统一社会信用代码" min-width="200"/>
      <el-table-column prop="merchantId" label="商户ID" min-width="200"/>
      <el-table-column prop="merchantName" label="商户名称" min-width="300"/>
      <el-table-column prop="contactPerson" label="联系人" min-width="100"/>
      <el-table-column prop="contactPhone" label="联系电话" min-width="120"/>
      <el-table-column prop="businessStartTime" label="经营开始时间" min-width="120"/>
      <el-table-column prop="reportStatus" label="报送状态" min-width="100">
        <template #default="scope">
          <el-tooltip
              class="item"
              effect="dark"
              :content="scope.row.reportMessage"
              placement="top"
              :disabled="!scope.row.reportMessage || scope.row.reportMessage.trim() === ''"
          >
            <el-tag :type="getStatusTagType(scope.row.reportStatus)">
              {{ getStatusLabel(scope.row.reportStatus) }}
            </el-tag>
          </el-tooltip>
        </template>
      </el-table-column>
      <el-table-column prop="createTime" label="创建时间" min-width="180"/>
      <el-table-column label="操作" width="300" fixed="right">
        <template #default="scope">
          <el-button size="small" type="warning" @click="reportDialog(scope.row)">
            报送
          </el-button>
          <el-button size="small" type="primary" @click="cancelDialog(scope.row)" :disabled="scope.row.reportStatus !== 4">
            作废
          </el-button>
          <el-button size="small" @click="showEditDialog(scope.row)">
            编辑
          </el-button>
          <el-button
              size="small"
              type="danger"
              @click="deleteRecord(scope.row)"
              :disabled="scope.row.reportStatus > 0">
            删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <div class="pagination-container">
      <el-pagination
          v-model:current-page="pagination.current"
          v-model:page-size="pagination.size"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
      />
    </div>
    <!--    </el-card>-->

    <!-- 新增/编辑对话框 -->
    <el-dialog
        v-model="dialogVisible"
        :title="dialogTitle"
        width="800px"
        @close="resetForm">
      <el-form
          ref="formRef"
          :model="form"
          :rules="rules"
          label-width="140px">
        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="纳税人名称" prop="taxpayerName">
              <el-input v-model="form.taxpayerName" placeholder="请输入纳税人名称"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="统一社会信用代码" prop="creditCode">
              <el-input v-model="form.creditCode" placeholder="请输入统一社会信用代码"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="商户ID" prop="merchantId">
              <el-input v-model="form.merchantId" placeholder="请输入商户ID"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="商户名称" prop="merchantName">
              <el-input v-model="form.merchantName" placeholder="请输入商户名称"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="联系人" prop="contactPerson">
              <el-input v-model="form.contactPerson" placeholder="请输入联系人"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话" prop="contactPhone">
              <el-input v-model="form.contactPhone" placeholder="请输入联系电话"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="是否办理市场主体登记" prop="hasRegistration">
              <el-select v-model="form.hasRegistration" placeholder="请选择">
                <el-option label="否" :value="0"/>
                <el-option label="是" :value="1"/>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="经营开始时间" prop="businessStartTime">
              <el-date-picker
                  v-model="form.businessStartTime"
                  type="date"
                  placeholder="请选择经营开始时间"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="操作类型代码" prop="operationTypeCode">
              <el-input v-model="form.operationTypeCode" placeholder="请输入操作类型代码"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="报送时间" prop="reportTime">
              <el-date-picker
                  v-model="form.reportTime"
                  type="date"
                  placeholder="请选择报送时间"
                  format="YYYY-MM-DD"
                  value-format="YYYY-MM-DD"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="详细地址" prop="detailedAddress">
          <el-input v-model="form.detailedAddress" placeholder="请输入详细地址"/>
        </el-form-item>

        <el-row :gutter="20">
          <el-col :span="12">
            <el-form-item label="网址">
              <el-input v-model="form.website" placeholder="请输入网址"/>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="专业服务机构标识">
              <el-input v-model="form.professionalServiceIdentifier" placeholder="请输入专业服务机构标识"/>
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="结算账户信息">
          <el-input v-model="form.settlementAccountInfo" placeholder="请输入结算账户信息"/>
        </el-form-item>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitForm" :loading="submitLoading">
            确定
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import {ref, onMounted, computed} from 'vue'
import {ElMessage, ElMessageBox} from 'element-plus'
import {Plus, Delete} from '@element-plus/icons-vue'
import {taxManagementApi, taxReportApi} from '../api'

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const submitLoading = ref(false)
const isEdit = ref(false)
const selectedIds = ref([])
const tableData = ref([])
const formRef = ref()

// 搜索表单
const searchForm = ref({
  taxpayerName: '',
  creditCode: '',
  merchantId: '',
  reportStatus: '',
  batchCode: ''
})

// 数据表单
const form = ref({
  taxpayerName: '',
  creditCode: '',
  merchantId: '',
  merchantName: '',
  detailedAddress: '',
  contactPerson: '',
  contactPhone: '',
  hasRegistration: 0,
  businessStartTime: '',
  operationTypeCode: '',
  website: '',
  professionalServiceIdentifier: '',
  settlementAccountInfo: '',
  reportTime: ''
})

// 分页配置
const pagination = ref({
  current: 1,
  size: 20,
  total: 0
})

// 表单验证规则
const rules = {
  taxpayerName: [
    {required: true, message: '请输入纳税人名称', trigger: 'blur'}
  ],
  creditCode: [
    {required: true, message: '请输入统一社会信用代码', trigger: 'blur'}
  ],
  merchantId: [
    {required: true, message: '请输入商户ID', trigger: 'blur'}
  ],
  merchantName: [
    {required: true, message: '请输入商户名称', trigger: 'blur'}
  ],
  contactPerson: [
    {required: true, message: '请输入联系人', trigger: 'blur'}
  ],
  contactPhone: [
    {required: true, message: '请输入联系电话', trigger: 'blur'}
  ],
  hasRegistration: [
    {required: true, message: '请选择是否办理市场主体登记', trigger: 'change'}
  ],
  businessStartTime: [
    {required: true, message: '请选择经营开始时间', trigger: 'change'}
  ],
  operationTypeCode: [
    {required: true, message: '请输入操作类型代码', trigger: 'blur'}
  ]
}

// 计算属性
const dialogTitle = computed(() => isEdit.value ? '编辑身份信息' : '新增身份信息')

// 方法
const loadData = async () => {
  loading.value = true
  try {
    const params = {
      page: pagination.value.current,
      size: pagination.value.size,
      ...searchForm.value
    }

    const response = await taxManagementApi.getIdentityList(params)
    if (response.data.code === 200) {
      tableData.value = response.data.data.records || []
      pagination.value.total = response.data.data.total || 0
    } else {
      ElMessage.error(response.data.message || '获取数据失败')
    }
  } catch (error) {
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败')
  } finally {
    loading.value = false
  }
}

const search = () => {
  pagination.value.current = 1
  loadData()
}

const resetSearch = () => {
  searchForm.value = {
    taxpayerName: '',
    creditCode: '',
    merchantId: '',
    reportStatus: ''
  }
  pagination.value.current = 1
  loadData()
}

const handleSizeChange = (size) => {
  pagination.value.size = size
  pagination.value.current = 1
  loadData()
}

const handleCurrentChange = (current) => {
  pagination.value.current = current
  loadData()
}

const handleSelectionChange = (selection) => {
  selectedIds.value = selection.map(item => item.id)
}

const showCreateDialog = () => {
  isEdit.value = false
  dialogVisible.value = true
}

const showEditDialog = (row) => {
  isEdit.value = true
  form.value = {...row}
  dialogVisible.value = true
}

const resetForm = () => {
  form.value = {
    taxpayerName: '',
    creditCode: '',
    merchantId: '',
    merchantName: '',
    detailedAddress: '',
    contactPerson: '',
    contactPhone: '',
    hasRegistration: 0,
    businessStartTime: '',
    operationTypeCode: '',
    website: '',
    professionalServiceIdentifier: '',
    settlementAccountInfo: '',
    reportTime: ''
  }
  if (formRef.value) {
    formRef.value.resetFields()
  }
}

const submitForm = async () => {
  if (!formRef.value) return

  try {
    await formRef.value.validate()
    submitLoading.value = true

    let response
    if (isEdit.value) {
      response = await taxManagementApi.updateIdentity(form.value.id, form.value)
    } else {
      response = await taxManagementApi.createIdentity(form.value)
    }

    if (response.data.code === 200) {
      ElMessage.success(isEdit.value ? '更新成功' : '创建成功')
      dialogVisible.value = false
      loadData()
    } else {
      ElMessage.error(response.data.message || '操作失败')
    }
  } catch (error) {
    console.error('提交失败:', error)
    ElMessage.error('提交失败')
  } finally {
    submitLoading.value = false
  }
}
// 上报
const reportDialog = async (row) => {
  try {
    await ElMessageBox.confirm(
        '确定要上报这条记录吗？',
        '确认上报',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )
    let reportVO = {
      id: row.id,
      batchCode: row.batchCode
    }
    const response = await taxReportApi.reportIdentityData(reportVO)
    if (response.data.data.failCount === 0) {
      ElMessage.success('上报成功')
      loadData()
    } else {
      ElMessage.error(response.data.data.errorMessage || '上报失败')
      loadData()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('上报失败:', error)
      ElMessage.error('上报失败')
    }
  }

}


const cancelDialog = async (row) => {
  try {
    await ElMessageBox.confirm(
        '确定要作废这条记录吗？',
        '确认作废',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )
    let reportVO = {
      ids: [row.id]
    }
    const response = await taxReportApi.identityCancel(reportVO)
    if (response.data.data.failCount === 0) {
      ElMessage.success('作废成功')
      loadData()
    } else {
      ElMessage.error(response.data.data.errorMessage || '作废失败')
      loadData()
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('作废失败:', error)
      ElMessage.error('作废失败')
    }
  }

}

const deleteRecord = async (row) => {
  try {
    await ElMessageBox.confirm(
        '确定要删除这条记录吗？',
        '确认删除',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    const response = await taxManagementApi.deleteIdentity(row.id)
    if (response.data.code === 200) {
      ElMessage.success('删除成功')
      loadData()
    } else {
      ElMessage.error(response.data.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除失败:', error)
      ElMessage.error('删除失败')
    }
  }
}

const batchDelete = async () => {
  if (selectedIds.value.length === 0) {
    ElMessage.warning('请选择要删除的记录')
    return
  }

  try {
    await ElMessageBox.confirm(
        `确定要删除选中的 ${selectedIds.value.length} 条记录吗？`,
        '确认批量删除',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }
    )

    const response = await taxManagementApi.batchDeleteIdentity(selectedIds.value)
    if (response.data.code === 200) {
      ElMessage.success('批量删除成功')
      selectedIds.value = []
      loadData()
    } else {
      ElMessage.error(response.data.message || '批量删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('批量删除失败:', error)
      ElMessage.error('批量删除失败')
    }
  }
}

const getStatusLabel = (status) => {
  const labels = {
    0: '待报送',
    1: '报送中',
    2: '报送成功',
    3: '报送失败',
    4: '待作废',
    5: '作废中',
    6: '作废成功',
    7: '作废失败'
  }
  return labels[status] || '未知'
}

const getStatusTagType = (status) => {
  const types = {
    0: 'info',
    1: 'warning',
    2: 'success',
    3: 'danger'
  }
  return types[status] || 'info'
}

// 生命周期
onMounted(() => {
  loadData()
})
</script>

<style scoped>
.tax-identity-management {
  padding: 0px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.search-bar {
  padding: 10px 0;
}

.search-form {
  display: flex;
  gap: 15px;
  flex-wrap: wrap;
  align-items: flex-end;
}

.search-form .el-form-item {
  margin-bottom: 0;
  min-width: 200px;
}

.search-form .el-button {
  border-radius: 8px;
  padding: 10px 20px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.search-form .el-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

.el-table {
  border-radius: 12px;
  overflow: hidden;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.el-table th {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%) !important;
  color: white !important;
  font-weight: 600;
  border: none;
}

.el-table td {
  border-bottom: 1px solid #f0f0f0;
}

.el-table tr:hover > td {
  background-color: #f8f9ff !important;
}

.el-button--small {
  border-radius: 6px;
  padding: 8px 16px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.el-button--small:hover {
  transform: translateY(-1px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
}

.pagination-container {
  margin-top: 25px;
  display: flex;
  justify-content: center;
  padding: 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
}

.el-pagination {
  --el-pagination-bg-color: transparent;
  --el-pagination-border-radius: 8px;
}

.el-pagination .el-pager li {
  border-radius: 6px;
  margin: 0 2px;
  transition: all 0.3s ease;
}

.el-pagination .el-pager li:hover {
  background-color: #f093fb;
  color: white;
}

.el-pagination .el-pager li.is-active {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
  color: white;
}

.header-actions {
  display: flex;
  gap: 10px;
  margin-top: 10px;
  margin-bottom: 10px;
}

/* 对话框样式 */
:deep(.el-dialog) {
  border-radius: 16px;
  overflow: hidden;
  box-shadow: 0 20px 60px rgba(0, 0, 0, 0.2);
}

:deep(.el-dialog__headerbtn .el-dialog__close) {
  color: white;
  font-size: 20px;
}

:deep(.el-dialog__body) {
  padding: 30px 24px;
  background: #fafbfc;
}

:deep(.el-dialog__footer) {
  padding: 20px 24px;
  background: white;
  border-top: 1px solid #f0f0f0;
}

.dialog-footer {
  text-align: right;
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}

.dialog-footer .el-button {
  border-radius: 8px;
  padding: 10px 24px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.dialog-footer .el-button:hover {
  transform: translateY(-1px);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
}

/* 表单样式 */
:deep(.el-form-item__label) {
  font-weight: 600;
  color: #333;
}

:deep(.el-input__wrapper) {
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
  transition: all 0.3s ease;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 2px rgba(240, 147, 251, 0.2);
}

:deep(.el-select .el-input__wrapper) {
  border-radius: 8px;
}

:deep(.el-date-editor .el-input__wrapper) {
  border-radius: 8px;
}

/* 状态标签样式 */
:deep(.el-tag) {
  border-radius: 20px;
  font-weight: 500;
  padding: 4px 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .tax-identity-management {
    padding: 15px;
  }

  .search-form {
    flex-direction: column;
    gap: 10px;
  }

  .search-form .el-form-item {
    min-width: auto;
    width: 100%;
  }

  .card-header {
    flex-direction: column;
    gap: 15px;
    text-align: center;
  }
}
</style>
